const Base = require('../base');
const createDOM = require('@antv/util/lib/dom/create-dom');
const modifyCSS = require('@antv/util/lib/dom/modify-css');
const GRID =
  'url()';

class Grid extends Base {
  init() {
    const graph = this.get('graph');
    const minZoom = graph.get('minZoom');
    const graphContainer = graph.get('container');
    const canvas = graph.get('canvas').get('el');
    const width = graph.get('width');
    const height = graph.get('height');
    const container = createDOM(
      '<div style="position: absolute; left:0;top:0;right:0;bottom:0;overflow: hidden;z-index: -1;"></div>'
    );
    const gridContainer = createDOM(
      '<div class="g6-grid" style="position:absolute;transform-origin: 0% 0% 0px; background-image: ' +
        GRID +
        '"></div>'
    );
    container.appendChild(gridContainer);
    modifyCSS(gridContainer, {
      width: width / minZoom + 'px',
      height: height / minZoom + 'px',
      left: 0,
      top: 0
    });
    graphContainer.insertBefore(container, canvas);
    this.set('container', container);
    this.set('gridContainer', gridContainer);
  }
  getEvents() {
    return { viewportchange: 'updateGrid' };
  }
  updateGrid(e) {
    const gridContainer = this.get('gridContainer');
    const matrix = e.matrix;
    const transform =
      'matrix(' +
      matrix[0] +
      ',' +
      matrix[1] +
      ',' +
      matrix[3] +
      ',' +
      matrix[4] +
      ',' +
      0 +
      ',' +
      0 +
      ')';
    modifyCSS(gridContainer, {
      transform
    });
  }
  getContainer() {
    return this.get('container');
  }
  destroy() {
    const graphContainer = this.get('graph').get('container');
    graphContainer.removeChild(this.get('container'));
  }
}

module.exports = Grid;
